import { Vector3 } from '@babylonjs/core/Maths/math.vector';
import { DefaultStage } from '../../default-stage';
import { Shell } from './shell';
import { AnimationFrame } from 'babylon-lib/index';
import { Random } from 'babylon-lib/tool/random';
import * as Data from '../../../data/data';
import { TargetManager } from '../target/target-manager';


class ShellManager {

    private static _salvo = 10;
    private static _shells: Shell[] = [];
    private static _position = new Vector3(0, 0, 20000);
    private static _index = 0;
    private static _reloadTime = 15000;
    private static _prepared = true;
    private static _req = {};
    private static _baseOffset = 900;
    private static _offset = new Vector3(this._baseOffset, 0, this._baseOffset);
    private static _convergence = 0.4;
    private static _pConvergence = 1;

    public static fire(): void {
        if (!this._prepared) return;
        this._index++;
        this._index %= this._salvo;
        const s = this._shells[this._index];
        if (!s.enabled) {
            this.fire();
            return;
        }
        this._prepared = false;
        this.setRangeData();
        s.fire(this._offset);
        Data.fireNumber.value++;
        AnimationFrame.throttleByTime(this._req, this._reloadTime, () => {
            this._prepared = true;
        }, false);
    }

    public static setInitialData(): void {
        const r = Math.pow(this._convergence, TargetManager.invalid);
        this._offset.x = Random.float(-this._baseOffset * r, this._baseOffset * r);
        this._offset.z = Random.float(-this._baseOffset * r, this._baseOffset * r);
        this._shells.forEach(s => s.setInitialData());
        this._pConvergence = 1;
    }

    private static setRangeData(): void {
        this._pConvergence *= this._convergence;
        this._shells.forEach(s => s.setRangeData(1 + Random.float(- this._pConvergence, this._pConvergence)));
    }

    public static initialize(stage: DefaultStage): void {
        this.initializeShells(stage);
    }

    private static initializeShells(stage: DefaultStage): void {
        for (let i = 0; i < this._salvo; i++) {
            const s = new Shell('shell' + i, stage);
            s.setPosition(this._position);
            s.setDirection(new Vector3().copyFrom(this._position).negateInPlace().normalize());
            this._shells.push(s);
        }
        // setTimeout(()=>{
        //     this._shells[0].explode(new Vector3(0,0,610));
        // },5000);
    }

}


export { ShellManager };